﻿using System;
using System.Collections;
using System.Collections.Generic;
using System.Data;
using System.Data.SqlClient;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;


namespace FirmaTransportowa
{
    public class User : IModel<User>
    {
        [System.ComponentModel.DisplayName("ID użytkownika")]
        public int id { get; set; }
        [System.ComponentModel.DisplayName("Login")]
        public String login { get; set; }
        [System.ComponentModel.DisplayName("Hasło")]
        public String password { get; set; }
        [System.ComponentModel.DisplayName("ID pracownika")]
        public Worker worker { get; set; }

        public User(int id, string login, string password, int worker_id)
        {
            this.id = id;
            this.login = login;
            this.password = password;
            this.worker = Worker.getById(worker_id);
        }

        public User()
        {

        }

        public string DisplayText
        {
            get
            {
                return this.login;
            }
        }

        public int ReturnValue
        {
            get
            {
                return this.id;
            }
        }

        public int save()
        {
            SqlConnection conn = SqlConnectionFactory.getConnection();

            int createdId = -1;

            try
            {
                conn.Open();
                SqlCommand cmd = new SqlCommand();
                bool newObject = false;

                if (User.getById(this.id) == null)
                {
                    cmd.CommandText = "INSERT INTO User_(login,password,worker_ID) VALUES(@login, @password, @worker_ID) SELECT CONVERT(int, SCOPE_IDENTITY())";
                    newObject = true;
                }
                else
                {
                    cmd.CommandText = "UPDATE User_ SET login=@login, password=@password, worker_ID=@worker_ID WHERE user_ID=@id";
                    cmd.Parameters.AddWithValue("@id", this.id);
                }

                cmd.Parameters.AddWithValue("@login", this.login);
                cmd.Parameters.AddWithValue("@password", this.password);
                cmd.Parameters.AddWithValue("@worker_ID", this.worker.id);
                cmd.Connection = conn;

                if (newObject)
                {
                    createdId = (int)cmd.ExecuteScalar();
                }
                else
                {
                    cmd.ExecuteNonQuery();
                }
            }
            catch (Exception ex)
            {
                System.Console.Write(ex.Message + "\n" + ex.StackTrace);
            }
            finally
            {
                conn.Close();
            }

            return createdId;
        }

        public static List<User> list()
        {
            List<User> list = new List<User>();

            SqlConnection conn = SqlConnectionFactory.getConnection();

            try
            {
                conn.Open();
                SqlCommand cmd = new SqlCommand("SELECT * FROM User_", conn);
                SqlDataReader reader = cmd.ExecuteReader(System.Data.CommandBehavior.Default);

                if (reader.HasRows)
                {
                    while (reader.Read())
                    {
                        User user = User.getById(int.Parse(reader["user_ID"].ToString()));

                        list.Add(user);
                    }
                }
                reader.Close();
            }
            catch (Exception e)
            {
                MessageBox.Show(e.Message + "\n" + e.StackTrace);
            }
            finally
            {
                conn.Close();
            }

            return list;
        }

        public static BindingSource getUsersForAdmin()
        {
            SqlConnection connection = SqlConnectionFactory.getConnection();
            BindingSource bindingSource = new BindingSource();

            try
            {
                connection.Open();
                SqlCommand command = new SqlCommand("SELECT user_ID, login, worker_ID FROM dbo.User_", connection);
                SqlDataAdapter dataAdapter = new SqlDataAdapter(command);
                DataTable dataTable = new DataTable();
                dataAdapter.Fill(dataTable);

                bindingSource.DataSource = dataTable;
            }
            catch (Exception e)
            {
                MessageBox.Show(e.Message + e.StackTrace);
            }
            finally
            {
                connection.Close();
            }

            return bindingSource;
        }

        public static bool checkIfRecordExists(string checkedText, string desiredTable)
        {
            bool result = false;

            SqlConnection dbConnection2 = SqlConnectionFactory.getConnection();
            dbConnection2.Open();

            try
            {
                string sql = "SELECT * FROM " + desiredTable + " WHERE login='" + checkedText + "'";

                SqlCommand cmd = new SqlCommand(sql, dbConnection2);
                SqlDataReader reader = cmd.ExecuteReader();

                if (reader.Read())
                {
                    result = true;
                    MessageBox.Show("Podany login juz istnieje w bazie!");
                }
                reader.Close();
            }
            finally
            {
                dbConnection2.Close();
            }

            return result;
        }

        public static User getByLogin(String login)
        {
            SqlConnection connection = SqlConnectionFactory.getConnection();

            try
            {
                connection.Open();
                SqlCommand cmd = new SqlCommand();
                cmd.CommandText = "SELECT * FROM User_ WHERE login=@login;";
                cmd.Parameters.AddWithValue("@login", login);
                cmd.Connection = connection;
                SqlDataReader reader = cmd.ExecuteReader(System.Data.CommandBehavior.SingleRow);

                if (reader.HasRows)
                {
                    reader.Read();
                    User user = new User();
                    user.id = int.Parse(reader["user_ID"].ToString());
                    user.login = reader["login"].ToString();
                    user.password = reader["password"].ToString();
                    user.worker = Worker.getById(int.Parse(reader["worker_ID"].ToString()));

                    connection.Close();
                    return user;
                }
            }
            catch (Exception e)
            {
                MessageBox.Show(e.Message + "\n" + e.StackTrace);
            }

            return null;
        }


        public static User getById(int id)
        {
            SqlConnection conn = SqlConnectionFactory.getConnection();

            try
            {
                if (id < 0)
                {
                    throw new ArgumentException();
                }

                conn.Open();
                SqlCommand cmd = new SqlCommand();
                cmd.CommandText = "SELECT * FROM User_ WHERE user_ID=@id;";
                cmd.Parameters.AddWithValue("@id", id);
                cmd.Connection = conn;
                SqlDataReader reader = cmd.ExecuteReader(System.Data.CommandBehavior.SingleRow);

                if (reader.HasRows)
                {
                    reader.Read();
                    User user = new User();
                    user.id = int.Parse(reader["user_ID"].ToString());
                    user.login = reader["login"].ToString();
                    user.password = reader["password"].ToString();
                    user.worker = Worker.getById(int.Parse(reader["worker_ID"].ToString()));

                    conn.Close();
                    return user;
                }
            }
            catch (Exception e)
            {
                MessageBox.Show(e.Message + "\n" + e.StackTrace);
            }
            finally
            {
                conn.Close();

            }

            return null;

        }

        public void delete()
        {
            SqlConnection conn = SqlConnectionFactory.getConnection();

            try
            {
                conn.Open();
                SqlCommand cmd = new SqlCommand();
                cmd.CommandText = "DELETE FROM User_ WHERE user_ID=@id";
                cmd.Parameters.AddWithValue("@id", this.id);

                cmd.Connection = conn;
                cmd.ExecuteNonQuery();
            }
            catch (Exception e)
            {
                MessageBox.Show(e.Message + "\n" + e.StackTrace);
            }
            finally
            {
                conn.Close();
            }
        }

        public int getOccupationId() {
            return this.worker.occupation.id;
        }

        public static Predicate<User> ById(int id)
        {
            return delegate(User user)
            {
                return user.id == id;
            };
        }

    }
}
